package com.customer.service.Impl;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.customer.entity.AIMessage;
import com.customer.entity.AISession;
import com.customer.mapper.AIMessageMapper;
import com.customer.mapper.AISessionMapper;
import com.customer.service.AISessionService;

import lombok.extern.slf4j.Slf4j;

/**
 * AI会话服务实现类
 */
@Service
@Slf4j
public class AISessionServiceImpl implements AISessionService {

    @Autowired
    private AISessionMapper aiSessionMapper;

    @Autowired
    private AIMessageMapper aiMessageMapper;

    @Override
    @Transactional
    public AISession createSession(Long userId, String role, String initialMessage) {
        // 生成新的会话ID
        String sessionId = "session_" + UUID.randomUUID().toString();

        // 从初始消息提取标题（最多30个字符）
        String title = initialMessage != null && initialMessage.length() > 0
                ? initialMessage.substring(0, Math.min(initialMessage.length(), 30)) + (initialMessage.length() > 30 ? "..." : "")
                : "新会话";

        // 创建会话
        AISession session = AISession.builder()
                .userId(userId)
                .sessionId(sessionId)
                .role(role)
                .title(title)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .status(0) // 0表示活跃
                .build();

        aiSessionMapper.insert(session);
        log.info("创建新AI会话: {}", session);

        return session;
    }

    @Override
    public List<AISession> getUserSessions(Long userId) {
        return aiSessionMapper.selectByUserId(userId);
    }

    @Override
    public List<AISession> getUserSessionsByRole(Long userId, String role) {
        return aiSessionMapper.selectByUserIdAndRole(userId, role);
    }

    @Override
    public AISession getSessionBySessionId(String sessionId) {
        return aiSessionMapper.selectBySessionId(sessionId);
    }

    @Override
    public void updateSessionTitle(String sessionId, String title) {
        AISession session = new AISession();
        session.setSessionId(sessionId);
        session.setTitle(title);
        session.setUpdateTime(LocalDateTime.now());
        aiSessionMapper.update(session);
    }

    @Override
    @Transactional
    public void deleteSession(Long id) {
        // 先删除会话的所有消息
        aiMessageMapper.deleteBySessionId(id);
        // 再删除会话
        aiSessionMapper.delete(id);
    }

    @Override
    public void saveMessage(AIMessage message) {
        aiMessageMapper.insert(message);

        // 更新会话的更新时间
        AISession session = new AISession();
        session.setId(message.getSessionId());
        session.setUpdateTime(LocalDateTime.now());
        aiSessionMapper.update(session);
    }

    @Override
    public List<AIMessage> getSessionMessages(Long sessionId) {
        return aiMessageMapper.selectBySessionId(sessionId);
    }
}